package de.lulusoft.anothertorrent.core.xmlrpc;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;

import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientException;
import org.apache.xmlrpc.client.XmlRpcStreamTransport;
import org.apache.xmlrpc.common.XmlRpcStreamRequestConfig;
import org.xml.sax.SAXException;

public class XmlRpcSocketTransport extends XmlRpcStreamTransport{

	private XmlRpcSocketClientConfig config = null;
	private Socket connection = null;
	private String cmdText = "";
	
	public XmlRpcSocketTransport(XmlRpcClient client) {
		super(client);
		this.config = (XmlRpcSocketClientConfig)client.getClientConfig();
	}


	@Override
	protected void close() throws XmlRpcClientException {
		try {
			if (connection != null && !connection.isClosed())
			connection.close();
		} catch (IOException e) {

		}
	}


	@Override
	protected InputStream getInputStream() throws XmlRpcException {
		try {
			InputStream input = connection.getInputStream();
			
			/*
	         * ignores response message of scgi server.
	         * Taken from nTorrent.
	         */
	        int c = 0;
	        while(c != -1){
	        	c = input.read();
	        	if(c == '\r' && input.read() == '\n')
	        		if(input.read() == '\r' && input.read() == '\n')
	        			break;
	        }
	        return input;
		} catch (Exception e) {
			throw new XmlRpcClientException("I/O error in server communication: " + e.getMessage(), e);
		}
	}


	@Override
	protected boolean isResponseGzipCompressed(XmlRpcStreamRequestConfig config) {
		return false;
	}


	@Override
	protected void writeRequest(ReqWriter writer) throws XmlRpcException,
			IOException, SAXException {
		connection = new Socket(config.getHost(), config.getPort());	
		OutputStream out = new OutputStream() {
		
			@Override
			public void write(int b) throws IOException {
				cmdText += (Character.toString(new Character((char) b)));		
			}
		};
		writer.write(out);
		
		StringBuffer buffer = new StringBuffer(SCGI.make(null,cmdText));
        OutputStream output = new BufferedOutputStream(connection.getOutputStream());
		
        output.write( buffer.toString().getBytes() );
        output.flush();
	}

}
